﻿using Mapster;
using Microsoft.EntityFrameworkCore;
using Quickly.Certs.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Quickly.Certs.EntityFrameworkCore.Data
{
    public class CertificateDataStore : ICertificateDataStore
    {
        protected virtual CertsContext Context { get; set; }
        public CertificateDataStore(CertsContext context)
        {
            Context = context;
        }

        public async Task<CertificateData?> LoadAsync(long id, CancellationToken cancellationToken)
        {
            var query = Context.CertificateFiles
                .AsNoTracking()
                .Where(x => x.Id == id && x.Deleted == false)
                .ProjectToType<CertificateData>();

            var data = await query.FirstOrDefaultAsync(cancellationToken);

            return data;
        }

        public async Task<long> SaveAsync(CertificateData data, CancellationToken cancellationToken)
        {
            var entity = new CertificateFile()
            {
                Data = data.Data,
                PfxPassword = data.PfxPassword
            };

            Context.Add(entity);

            await Context.SaveChangesAsync(cancellationToken);

            return entity.Id;
        }

        public async Task<List<CertificateData>> LoadAsync(List<long> ids, CancellationToken cancellationToken)
        {
            var query = Context.CertificateFiles
                .AsNoTracking()
                .Where(x => ids.Contains(x.Id) && x.Deleted == false)
                .ProjectToType<CertificateData>();

            var datas = await query.ToListAsync(cancellationToken);

            return datas;
        }

        public async Task DeleteAsync(List<long> ids, CancellationToken cancellationToken)
        {
            if(ids == null || ids.Count == 0)
            {
                return;
            }

            var datas = await Context.CertificateFiles.Where(x => ids.Contains(x.Id)).ToListAsync(cancellationToken);

            foreach (var data in datas)
            {
                data.Deleted = true;
                data.LastModified = DateTimeOffset.UtcNow;
            }

            await Context.SaveChangesAsync(cancellationToken);
        }
    }
}
